Golang encoding/xml.Encoder.Indent() function example
package encoding/xml
Indent sets the encoder to generate XML in which each element begins on a new indented line that starts with prefix and is followed by one or more copies of indent according to the nesting depth.
Golang encoding/xml.Encoder.Indent() function usage example
package main
import (
"encoding/xml"
"fmt"
"os"
"reflect"
)
type Address struct {
City, State string
City, State string
}
type Person struct {
XMLName xml.Name `xml:"person"`
Id int `xml:"id,attr"`
FirstName string `xml:"name>first"`
LastName string `xml:"name>last"`
Age int `xml:"age"`
Height float32 `xml:"height,omitempty"`
Married bool
Address
Comment string `xml:",comment"`
}
func main() {
v := &Person{Id: 13, FirstName: "John", LastName: "Doe", Age: 42}
v.Comment = " Need more details. "
v.Address = Address{"Hanga Roa", "Easter Island"}
encoder := xml.NewEncoder(os.Stdout)
encoder.Indent(" ", " ") // <---- here
newtoken := xml.StartElement{
Name : xml.Name{
Space: "",
Local: "location",
},
}
if err := encoder.EncodeToken(newtoken); err != nil {
fmt.Println(err)
}
start := xml.StartElement{
Name: xml.Name{
Space: "",
Local: reflect.Indirect(reflect.ValueOf(v)).Type().Name(),
},
Attr: []xml.Attr{{xml.Name{"", "xmlns"}, "https://socketloop.com/xmldoc/2014-09-01/"}},
}
if err := encoder.EncodeElement(v, start); err != nil {
fmt.Println(err)
}
encoder.Flush()
}
Reference :
Advertisement
Something interesting
Tutorials
+9.1k Golang : io.Reader causing panic: runtime error: invalid memory address or nil pointer dereference
+10.5k Swift : Convert (cast) String to Integer
+12.6k Golang : Transform comma separated string to slice example
+8.2k Golang : Add build version and other information in executables
+7.5k Gogland : Single File versus Go Application Run Configurations
+10.6k Golang : Bubble sort example
+32.2k Golang : Convert []string to []byte examples
+7.5k Golang : Shuffle strings array
+3.7k Java : Random alphabets, alpha-numeric or numbers only string generator
+6.3k WARNING: UNPROTECTED PRIVATE KEY FILE! error message
+7.7k Golang : Error reading timestamp with GORM or SQL driver
+9k Golang : Go as a script or running go with shebang/hashbang style